package com.huibao.hulibao.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.BaseColumns;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v4.content.ContextCompat;

import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.bumptech.glide.Glide;
import com.example.zhouwei.library.CustomPopWindow;
import com.huibao.hulibao.R;
import com.huibao.hulibao.adapter.BindClientLvAdapter;
import com.huibao.hulibao.adapter.PhotoGvAdapter;
import com.huibao.hulibao.adapter.ServerLvAdapter;
import com.huibao.hulibao.adapter.StartHuliLvAdapter;
import com.huibao.hulibao.adapter.StartHuliPopNextLvAdapter;
import com.huibao.hulibao.constant.GlobalConstants;
import com.huibao.hulibao.entity.HuLiBindMomEntity;
import com.huibao.hulibao.entity.HuLiEntity;
import com.huibao.hulibao.entity.HuLiLogEntity;
import com.huibao.hulibao.entity.JiaoYanEntity;
import com.huibao.hulibao.entity.LoginEntity;
import com.huibao.hulibao.entity.ResultEntity;
import com.huibao.hulibao.entity.ScanEntity;
import com.huibao.hulibao.utils.DialogUtils;
import com.huibao.hulibao.utils.MyUtils;
import com.huibao.hulibao.utils.PreUtils;
import com.huibao.hulibao.utils.T;
import com.huibao.hulibao.view.MyGridView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;

/**
 * Created by lizhaoyong on 2018/5/11.
 * 确认开始护理页面
 */
public class StartHuliActivity extends BaseActivity {

    @BindView(R.id.iv_back)
    ImageView iv_back;
    @BindView(R.id.lv_start_huli)
    ListView lv_start_huli;
    @BindView(R.id.tv_room_number)
    TextView tv_room_number;
    @BindView(R.id.tv_mom_name)
    TextView tv_mom_name;
    @BindView(R.id.tv_baby_name)
    TextView tv_baby_name;
    @BindView(R.id.tv_content)
    TextView tv_content;
    @BindView(R.id.tv_jiaoyan)
    TextView tv_jiaoyan;
    @BindView(R.id.iv_title)
    ImageView iv_title;
    @BindView(R.id.tv_start)
    TextView tv_start;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.tv_log_title)
    TextView tv_log_title;
    @BindView(R.id.tv_benhuli)
    TextView tv_benhuli;
    @BindView(R.id.ll_main)
    LinearLayout ll_main;
    @BindView(R.id.tv_no_data)
    TextView tv_no_data;

    // 网络请求加载对话框
    private Dialog myDialog;

    private HuLiEntity.HuLiData hd;
    // 校验实体对象
    private JiaoYanEntity jye;
    // 是否需要校验的判断
    private boolean isNeedCheck = true;
    // 校验返回标识
    private int CHECK_REQUESTCODE = 333;

    private StartHuliPopNextLvAdapter startHuliPopNextLvAdapter;


    // 图片存放集合
    private ArrayList<Bitmap> al_Bitmaps;
    private ArrayList<String> al_imgs;
    // 选中图片的下标
    private int position_img = 0;
    protected static Uri tempUri;
    // 图片的选中状态
    protected static final int CHOOSE_PICTURE = 7;
    protected static final int TAKE_PICTURE = 8;
    private static final int CROP_SMALL_PICTURE = 9;
    // 弹出拍照取照片的POPWINDOW
    private PopupWindow pop_photo;
    private LinearLayout ll_popwindow_photo;
    private MyGridView gv_photo;
    // 添加还是修改的判断 默认是添加
    private boolean isNew = true;

    private String pid;
    private String session;
    private String type;
    public String nid;
    private String customerid;
    private String motherid;
    private String babyid;
    private String roomid;
    private String mom_name;
    private String baby_mom;
    private String room_name;
    private String title;
    private String pic;
    private String baby_name;

    private CustomPopWindow popWindow;

    // 登录信息
    private LoginEntity le;

    // 用于修改护理数据的
    public String rid;

    private ListView lv;
    // 开始时间
    private String startime;

    // 返回码
    private int requestCode = 1;
    // 重新赋值数据模型的下标索引
    private int position = -1;

    private String type_id;

    // 区分本护理项和全部日志
    private int type_getData = 1;

    @OnClick(R.id.iv_back)
    public void back() {
        finish();
    }

    @OnClick(R.id.tv_log_title)
    public void typeOne() {
        type_getData = 1;
        int bottom = tv_log_title.getPaddingBottom();
        int top = tv_log_title.getPaddingTop();
        int right = tv_log_title.getPaddingRight();
        int left = tv_log_title.getPaddingLeft();

        tv_log_title.setTextColor(Color.parseColor("#ffffff"));
        tv_benhuli.setTextColor(Color.parseColor("#dfdfdf"));
        tv_log_title.setBackgroundResource(R.drawable.corner_view_nurse_title_selected);
        tv_benhuli.setBackgroundResource(R.drawable.corner_view_nurse_title_no_selected);
        tv_benhuli.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
        tv_log_title.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
        tv_log_title.setPadding(left, top, right, bottom);
        tv_benhuli.setPadding(left, top, right, bottom);

        getHuliLogData(nid);


    }

    @OnClick(R.id.tv_benhuli)
    public void typeTwo() {
        type_getData = 2;
        int bottom = tv_log_title.getPaddingBottom();
        int top = tv_log_title.getPaddingTop();
        int right = tv_log_title.getPaddingRight();
        int left = tv_log_title.getPaddingLeft();
        tv_log_title.setTextColor(Color.parseColor("#dfdfdf"));
        tv_benhuli.setTextColor(Color.parseColor("#ffffff"));

        tv_benhuli.setBackground(getResources().getDrawable(R.drawable.corner_view_nurse_title_selected));
        tv_log_title.setBackground(getResources().getDrawable(R.drawable.corner_view_nurse_title_no_selected));
        tv_benhuli.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
        tv_log_title.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);

        tv_log_title.setPadding(left, top, right, bottom);
        tv_benhuli.setPadding(left, top, right, bottom);

        getHuliLogData("0");
    }


    @OnClick(R.id.tv_start)
    public void start() {
        if (isNeedCheck) {
            // 处理二维码校验逻辑
            if (jye != null) {
                Intent intent = new Intent(getApplicationContext(), ScanListActivity.class);
                ArrayList<ScanEntity> al = new ArrayList<>();
                if (jye.Message.start.contains(";")) {
                    String[] arr = jye.Message.start.split(";");
                    for (int i = 0; i < arr.length; i++) {
                        ScanEntity se = new ScanEntity();
                        se.setScanLabel(arr[i]);
                        al.add(se);
                    }
                } else {
                    ScanEntity se = new ScanEntity();
                    se.setScanLabel(jye.Message.start);
                    al.add(se);
                }

                intent.putExtra("Huli", al);
                intent.putExtra("boolean_Huli", true);
                startActivityForResult(intent, CHECK_REQUESTCODE);
            }

        } else {
            // 记录开始时间
            startime = MyUtils.getFormatTimeToString(System.currentTimeMillis()).replace(":", "%3A");
            // 如果是点击了修改就重置数据模型将模式改为添加
            if (isNew == false) {
                dataReset();
                isNew = true;
            }
            // 显示选中参数的对话框
            if (hd.v.size() > 0) {
                showStartPop(0, isNew);
            }
        }
    }


    // 显示客户的popwindow
    // position 显示的位置
    // isNew 新增还是修改

    public void showStartPop(int position, final boolean isNew) {
        WindowManager wm = (WindowManager) this
                .getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        int heigh = wm.getDefaultDisplay().getHeight();
        popWindow = new CustomPopWindow.PopupWindowBuilder(StartHuliActivity.this)
                .setView(R.layout.popwindow_start_huli)
                .setFocusable(true)
                .size(width, (int) (heigh * 0.98))
                .setOutsideTouchable(true)
                // pop消失监听
                .setOnDissmissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {

                    }
                })
                .create();
        lv = (ListView) popWindow.getPopupWindow().getContentView().findViewById(R.id.lv_pop_start_huli);
        gv_photo = (MyGridView) popWindow.getPopupWindow().getContentView().findViewById(R.id.gv_photo);
        final RelativeLayout pop_rl_main = (RelativeLayout) popWindow.getPopupWindow().getContentView().findViewById(R.id.pop_rl_main);

        TextView tv_close = (TextView) popWindow.getPopupWindow().getContentView().findViewById(R.id.tv_close);
        TextView tv_title = (TextView) popWindow.getPopupWindow().getContentView().findViewById(R.id.tv_title);
        if (isNew) {
            tv_title.setText("执行任务（添加）");
            tv_title.setTextColor(getResources().getColor(R.color.green));
        } else {
            tv_title.setText("执行任务（修改）");
            tv_title.setTextColor(getResources().getColor(R.color.red));
        }
        tv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popWindow.dissmiss();
            }
        });

        popWindow.showAtLocation(ll_main, Gravity.CENTER, 0, 0);
//        for (int i = 0; i < hd.v.size(); i++) {
//            LogUtils.d("content = " + hd.v.get(i).selected_str);
//        }

        startHuliPopNextLvAdapter = new StartHuliPopNextLvAdapter(hd.v, getApplicationContext(), this);
        lv.setAdapter(startHuliPopNextLvAdapter);
        // 设置第几行可见-1行
        lv.setSelection(position - 1);
        TextView tv_finish = (TextView) popWindow.getPopupWindow().getContentView().findViewById(R.id.tv_finish);

        // 确认开始护理
        tv_finish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 提示框弹出
                AlertDialog.Builder ab = new AlertDialog.Builder(StartHuliActivity.this);
                ab.setPositiveButton("确认提交", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if (isNew) {
                            confirmHuli();
                        } else {
                            changeHuliData();
                        }
                    }
                });
                ab.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                });
                ab.setTitle("提示");
                ab.show();
            }
        });

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        popWindow.dissmiss();
                    }
                }, 500);
                // position = i;
                HuLiEntity.HuLiDetailData hdd = hd.v.get(i);
                Intent intent = new Intent(getApplicationContext(), StartHuliSelectedActivity.class);
                intent.putExtra("selected_data", hdd);
                // 将点击的索引传递过去
                intent.putExtra("position", String.valueOf(i));
                // LogUtils.d("position = " + position);
                startActivityForResult(intent, requestCode);
                overridePendingTransition(0, 0);//去掉切换动画关键


            }
        });

        // 设置显示位置
        popWindow.showAsDropDown(tv_title, -300, 100);
        // popWindow.showAsDropDown(tv_title, 0, 0);


        initPopWindowPhoto();

        gv_photo.setSelector(new ColorDrawable(Color.TRANSPARENT));
        gv_photo.setAdapter(new PhotoGvAdapter(al_Bitmaps, getApplicationContext(), al_imgs, 5));
        gv_photo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                position_img = i;
                ll_popwindow_photo.startAnimation(AnimationUtils.loadAnimation(
                        getApplicationContext(), R.anim.activity_translate_in));
                pop_photo.showAtLocation(ll_main, Gravity.BOTTOM, 0, 0);
                // closeKeybord();
            }
        });
    }

    // 获取的单条信息
    public void getSingleMsgFromServer(String rid) {
        this.rid = rid;
        RequestParams params = new RequestParams(GlobalConstants.URL);
        params.setCacheMaxAge(0);
        showDialog();
        JSONObject object = new JSONObject();
        try {
            object.put("rid", rid);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        params.addBodyParameter("q", session + GlobalConstants.URL_SIGNLE_MSG + object.toString());
        // LogUtils.d("params = " + params.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                closeDialog();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(result);
                    LogUtils.d("result = " + jsonObject.toString());

                    if (jsonObject.get("State").equals(GlobalConstants.SUCCESS_CODE)) {
                        // 重置数据模型
                        dataReset();
                        isNew = false;
                        // 将获取的数值赋值到模型中去
                        for (int i = 0; i < hd.v.size(); i++) {
                            if (jsonObject.toString().contains(hd.v.get(i).nk)) {
                                hd.v.get(i).selected_str = (String) jsonObject.getJSONObject("Message").get(hd.v.get(i).nk);
                            }

                            if (!jsonObject.getJSONObject("Message").get(hd.v.get(i).nk).equals("")) {
                                hd.v.get(i).input_data = (String) jsonObject.getJSONObject("Message").get(hd.v.get(i).nk);
                            }


                        }

                        // 将获取的数值
                        String imgs = (String) jsonObject.getJSONObject("Message").get("ImgUrl");
                        if (!imgs.equals("")) {
                            String[] arr = imgs.split("\\|");
                            for (int i = 0; i < arr.length; i++) {
                                al_imgs.add(arr[i]);
                            }
                        }
                        showStartPop(position, isNew);

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                closeDialog();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                closeDialog();
            }

            @Override
            public void onFinished() {
                closeDialog();
            }
        });
    }

//    // 记录用户输入的信息
//    public void RecordInputData(int position, String input_data) {
//        hd.v.get(position).input_data = input_data;
//    }

    // 跳转到web页面
    public void jumpWeb() {
        Intent intent = new Intent(getApplicationContext(), WebViewActivity.class);
        intent.putExtra("url", GlobalConstants.HOST + "AppWap/PDA_APP/WebTools/ShowNurseDetail.aspx?ss=" + le.Message.Session + "&nid=" + nid);
        startActivity(intent);
    }


    public void changeHuliData() {
        // 处理listview中edittext复用数据混乱，edittext数据赋值
        ArrayList<HuLiEntity.HuLiDetailData> mDatas = startHuliPopNextLvAdapter.mDatas;
        for (int i = 0; i < mDatas.size(); i++) {
            HuLiEntity.HuLiDetailData huLiDetailData = mDatas.get(i);
            // 不给单选和多选的数据进行赋值
            if (huLiDetailData.t.equals("rad") || huLiDetailData.t.equals("chb")) {

            } else {
                if (huLiDetailData.input_data != null) {
                    hd.v.get(i).selected_str = huLiDetailData.input_data;
                }
            }
        }

        // 必填数据校验
        for (int i = 0; i < hd.v.size(); i++) {
            if (hd.v.get(i).r.equals("1")) {
//                LogUtils.d("必须填写的字段 = " + hd.v.get(i).nk);
//                LogUtils.d("必须填写的数据 = " + hd.v.get(i).selected_str);
                if (hd.v.get(i).selected_str == null || hd.v.get(i).selected_str.equals("")) {
                    T.show(getApplicationContext(), getString(R.string.hongseshujubixutianxie), 0);
                    return;
                }
            }
            String select = hd.v.get(i).selected_str;
            if (select == null) {
                hd.v.get(i).selected_str = "";
            }
        }

        RequestParams params = new RequestParams(GlobalConstants.URL);
        params.setCacheMaxAge(0);
        showDialog();
        // 常规类型
        JSONObject object = new JSONObject();
        // 数组类型
        List<JSONObject> jsonObjects = new ArrayList<JSONObject>();
        try {
            object.put("rid", rid);

            for (int i = 0; i < hd.v.size(); i++) {
                JSONObject jsonObject_arr = new JSONObject();
                if (hd.v.get(i).selected_str == null) {
                    jsonObject_arr.put(hd.v.get(i).nk, "");
                } else {
                    jsonObject_arr.put(hd.v.get(i).nk, hd.v.get(i).selected_str);
                }
                jsonObjects.add(jsonObject_arr);
            }

            // 添加图片参数
            if (al_imgs.size() > 0) {
                JSONObject jsonObject_arr = new JSONObject();
                if (al_imgs.size() == 1) {
                    jsonObject_arr.put("imgurl", al_imgs.get(0));
                } else {
                    String str = "";
                    for (int i = 0; i < al_imgs.size(); i++) {
                        if (i != al_imgs.size() - 1) {
                            str += al_imgs.get(i) + "|";
                        } else {
                            str += al_imgs.get(i);
                        }
                    }
                    jsonObject_arr.put("imgurl", str);
                }
                jsonObjects.add(jsonObject_arr);
            }
            // LogUtils.d("jsonObjects = " + jsonObjects.toString());
            String str = jsonObjects.toString().replace("[", "").replace("]", "").replace("{", "").replace("}", "");
            // LogUtils.d("jsonObjects = " + "{" + str + "}");
            object.put("data", "{" + str + "}");

            // 强行转化为对象格式的字符串
            params.addBodyParameter("q", session + GlobalConstants.URL_CHANGE_MSG + object.toString().replace("\\", "").replace("\"{", "{").replace("}\"", "}"));
            LogUtils.d("params = " + params.toString());
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    closeDialog();
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(result);
                        ResultEntity re = GlobalConstants.gson.fromJson(jsonObject.toString(), ResultEntity.class);
                        if (re.State.equals(GlobalConstants.SUCCESS_CODE)) {
                            isNew = true;
                            // 重置数据
                            dataReset();
                            jumpWeb();
                            T.show(getApplicationContext(), getString(R.string.chaozuochenggong), 0);
                            popWindow.dissmiss();
                            // 获取护理日志数据
                            if (type_getData == 1) {
                                getHuliLogData(nid);
                            } else if (type_getData == 2) {
                                getHuliLogData("0");
                            }

                        } else {
                            popWindow.dissmiss();
                            T.show(getApplicationContext(), re.Message, 0);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    closeDialog();
                }

                @Override
                public void onCancelled(CancelledException cex) {
                    closeDialog();
                }

                @Override
                public void onFinished() {
                    closeDialog();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public void confirmHuli() {
        // 处理listview中edittext复用数据混乱，edittext数据赋值
        ArrayList<HuLiEntity.HuLiDetailData> mDatas = startHuliPopNextLvAdapter.mDatas;
        for (int i = 0; i < mDatas.size(); i++) {
            HuLiEntity.HuLiDetailData huLiDetailData = mDatas.get(i);
            // 单选或多选不用重新赋值
            if (huLiDetailData.t.equals("rad") || hd.t.equals("chb")) {

            } else {
                if (huLiDetailData.input_data != null) {
                    hd.v.get(i).selected_str = huLiDetailData.input_data;
                }
            }
        }
        // 必填数据校验
        for (int i = 0; i < hd.v.size(); i++) {
            if (hd.v.get(i).r.equals("1")) {
//                LogUtils.d("必须填写的字段 = " + hd.v.get(i).nk);
//                LogUtils.d("必须填写的数据 = " + hd.v.get(i).selected_str);
                if (hd.v.get(i).selected_str == null || hd.v.get(i).selected_str.equals("")) {
                    T.show(getApplicationContext(), getString(R.string.hongseshujubixutianxie), 0);
                    return;
                }
            }
        }
//        if (true) {
//            return;
//        }

        RequestParams params = new RequestParams(GlobalConstants.URL);
        params.setCacheMaxAge(0);
        showDialog();
        // 常规类型
        JSONObject object = new JSONObject();
        // 数组类型
        List<JSONObject> jsonObjects = new ArrayList<JSONObject>();
        String endtime = MyUtils.getFormatTimeToString(System.currentTimeMillis()).replace(":", "%3A");
        try {
            object.put("type", type);
            object.put("nurseid", nid);
            object.put("nursename", type);
            object.put("roomid", roomid);
            object.put("roomname", room_name);
            object.put("matherid", motherid);
            object.put("mathername", mom_name);
            object.put("babyid", babyid);
            object.put("babyname", baby_mom);
            object.put("startime", startime);
            object.put("endtime", endtime);
            // 选中参数
            // object.put("data", params);
            for (int i = 0; i < hd.v.size(); i++) {
                JSONObject jsonObject_arr = new JSONObject();
                if (hd.v.get(i).selected_str == null) {
                    jsonObject_arr.put(hd.v.get(i).nk, "");
                } else {
                    jsonObject_arr.put(hd.v.get(i).nk, hd.v.get(i).selected_str);
                }
                jsonObjects.add(jsonObject_arr);
            }

            // 添加图片参数
            if (al_imgs.size() > 0) {
                JSONObject jsonObject_arr = new JSONObject();
                if (al_imgs.size() == 1) {
                    jsonObject_arr.put("imgurl", al_imgs.get(0));
                } else {
                    String str = "";
                    for (int i = 0; i < al_imgs.size(); i++) {
                        if (i != al_imgs.size() - 1) {
                            str += al_imgs.get(i) + "|";
                        } else {
                            str += al_imgs.get(i);
                        }
                    }
                    jsonObject_arr.put("imgurl", str);
                }
                jsonObjects.add(jsonObject_arr);
            }
            // LogUtils.d("jsonObjects = " + jsonObjects.toString());
            String str = jsonObjects.toString().replace("[", "").replace("]", "").replace("{", "").replace("}", "");
            // LogUtils.d("jsonObjects = " + "{" + str + "}");
            object.put("data", "{" + str + "}");

        } catch (JSONException e) {
            e.printStackTrace();
        }
        // 强行转化为对象格式的字符串
        params.addBodyParameter("q", session + GlobalConstants.URL_START_HULI + object.toString().replace("\\", "").replace("\"{", "{").replace("}\"", "}"));
        LogUtils.d("params = " + params.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                closeDialog();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(result);
                    LogUtils.d("result = " + jsonObject.toString());
                    ResultEntity re = GlobalConstants.gson.fromJson(jsonObject.toString(), ResultEntity.class);
                    if (re.State.equals(GlobalConstants.SUCCESS_CODE)) {
                        jumpWeb();
                        // 重置数据
                        dataReset();
                        T.show(getApplicationContext(), getString(R.string.chaozuochenggong), 0);
                        popWindow.dissmiss();
                        // 获取护理日志数据
                        if (type_getData == 1) {
                            getHuliLogData(nid);
                        } else if (type_getData == 2) {
                            getHuliLogData("0");
                        }

                    } else {
                        popWindow.dissmiss();
                        T.show(getApplicationContext(), re.Message, 0);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                closeDialog();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                closeDialog();
            }

            @Override
            public void onFinished() {
                closeDialog();
            }
        });
    }


    // 数据重置
    public void dataReset() {
        if (hd != null) {
            for (int i = 0; i < hd.v.size(); i++) {
                HuLiEntity.HuLiDetailData hdd = hd.v.get(i);
                hdd.selected_str = "";
                hdd.input_data = "";
            }
            al_Bitmaps.clear();
            al_imgs.clear();

        }
    }


    public void initPopWindowPhoto() {
        pop_photo = new PopupWindow(getApplicationContext());
        View view = this.getLayoutInflater().inflate(R.layout.popwindow_select_photo, null);
        ll_popwindow_photo = (LinearLayout) view.findViewById(R.id.ll_popwindow_photo);
        pop_photo.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        pop_photo.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        pop_photo.setBackgroundDrawable(new ColorDrawable(0xc0cccccc));
        pop_photo.setFocusable(true);
        pop_photo.setOutsideTouchable(true);
        pop_photo.setContentView(view);

        RelativeLayout parent = (RelativeLayout) view.findViewById(R.id.parent);
        Button bt1 = (Button) view.findViewById(R.id.item_popupwindows_camera);
        Button bt2 = (Button) view.findViewById(R.id.item_popupwindows_Photo);
        Button bt3 = (Button) view.findViewById(R.id.item_popupwindows_cancel);
        parent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop_photo.dismiss();
                ll_popwindow_photo.clearAnimation();
            }
        });

        // 拍照
        bt1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 请求开启拍照权限和读写权限
                if (ContextCompat.checkSelfPermission(StartHuliActivity.this, Manifest.permission.CAMERA)
                        != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(StartHuliActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    // 请求开启相机权限
                    PermissionGen.needPermission(StartHuliActivity.this, 105,
                            new String[]{
                                    Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}

                    );
                } else {
                    Intent openCameraIntent = new Intent(
                            MediaStore.ACTION_IMAGE_CAPTURE);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

                    } else {
                        tempUri = Uri.fromFile(new File(Environment
                                .getExternalStorageDirectory(), "image.jpg"));
                        openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
                    }
                    startActivityForResult(openCameraIntent, TAKE_PICTURE);
                    pop_photo.dismiss();
                    ll_popwindow_photo.clearAnimation();
                }
            }
        });

        // 相册获取
        bt2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 读取本地相册权限
                if (ContextCompat.checkSelfPermission(StartHuliActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    // 请求开启本地相册权限
                    PermissionGen.needPermission(StartHuliActivity.this, 107,
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}
                    );
                } else {
                    // cropImageUtils.openAlbum();
                    Intent openAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT);
                    openAlbumIntent.setType("image/*");
                    overridePendingTransition(R.anim.activity_translate_in,
                            R.anim.activity_translate_out);
                    startActivityForResult(openAlbumIntent, CHOOSE_PICTURE);
                    pop_photo.dismiss();
                    ll_popwindow_photo.clearAnimation();
                }
            }
        });
        bt3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop_photo.dismiss();
                ll_popwindow_photo.clearAnimation();
            }
        });
    }

    // 提交单个图片到服务器
    public void postPicToServer() {
        showDialog();
        RequestParams params = new RequestParams(GlobalConstants.URL_PIC_CACHE);
        params.setCacheMaxAge(0);
        params.setMultipart(true);
        params.addBodyParameter("sign", "ISVIP_URYRHEUYRYRTHYEY8987656");
        params.addBodyParameter("type", "png");
        String path = Environment.getExternalStorageDirectory()
                + File.separator + "hulibao_check" + File.separator + "check_pic.jpg";
        try {
            params.addBodyParameter("file", readStream(path), "image/jpg");
        } catch (Exception e) {
            e.printStackTrace();
        }
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                al_imgs.add(position_img, result);
                LogUtils.d("result = " + result);
                closeDialog();
                // arr_pic[position] = result;
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                closeDialog();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                closeDialog();
            }

            @Override
            public void onFinished() {
                closeDialog();
            }
        });
    }

    public static byte[] readStream(String imagepath) throws Exception {
        FileInputStream fs = new FileInputStream(imagepath);
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while (-1 != (len = fs.read(buffer))) {
            outStream.write(buffer, 0, len);
        }
        outStream.close();
        fs.close();
        return outStream.toByteArray();
    }

    /**
     * 裁剪图片方法实现
     */
    protected void startPhotoZoom(Uri uri) {
        if (uri == null) {
            return;
        }
        tempUri = uri;
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 500);
        intent.putExtra("outputY", 500);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, CROP_SMALL_PICTURE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults) {
        PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    @PermissionSuccess(requestCode = 107)
    public void doOpenLocationPhoto() {
        Intent openAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT);
        openAlbumIntent.setType("image/*");
        overridePendingTransition(R.anim.activity_translate_in,
                R.anim.activity_translate_out);
        startActivityForResult(openAlbumIntent, CHOOSE_PICTURE);
        pop_photo.dismiss();
        ll_popwindow_photo.clearAnimation();
    }

    @PermissionFail(requestCode = 107)
    public void doFailLocationPhoto() {
        T.show(getApplicationContext(), "读取本地图片权限被拒绝！", 0);
    }


    @PermissionSuccess(requestCode = 105)
    public void doSomething() {
        T.show(getApplicationContext(), "相机权限已开启", 0);
        // cropImageUtils.takePhoto();
        Intent openCameraIntent = new Intent(
                MediaStore.ACTION_IMAGE_CAPTURE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

        } else {
            tempUri = Uri.fromFile(new File(Environment
                    .getExternalStorageDirectory(), "image.jpg"));
            openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
        }
        startActivityForResult(openCameraIntent, TAKE_PICTURE);
        pop_photo.dismiss();
        ll_popwindow_photo.clearAnimation();
    }

    @PermissionFail(requestCode = 105)
    public void doFailSomething() {
        T.show(getApplicationContext(), "相机权限打开失败！", 0);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start_huli);
        ButterKnife.bind(this);

        le = (LoginEntity) PreUtils.getObject(getApplicationContext(), "LoginEntity");

        pid = getIntent().getStringExtra("pid");
        nid = getIntent().getStringExtra("nid");
        type_id = nid;
        session = getIntent().getStringExtra("session");
        type = getIntent().getStringExtra("type");
        hd = (HuLiEntity.HuLiData) getIntent().getSerializableExtra("mom_data");
        customerid = getIntent().getStringExtra("customerid");
        roomid = getIntent().getStringExtra("roomid");
        motherid = getIntent().getStringExtra("motherid");
        babyid = getIntent().getStringExtra("babyid");
        mom_name = getIntent().getStringExtra("mom_name");
        baby_mom = getIntent().getStringExtra("baby_mom");
        baby_name = getIntent().getStringExtra("baby_name");
        room_name = getIntent().getStringExtra("room_name");
        title = getIntent().getStringExtra("title");
        pic = getIntent().getStringExtra("pic");

        // 初始化拍照相关
        al_Bitmaps = new ArrayList<Bitmap>();
        al_imgs = new ArrayList<String>();

        if (pic != null && !pic.equals("")) {
            Glide.with(this).load(GlobalConstants.HOST + pic).into(iv_title);
        }

        tv_mom_name.setText(mom_name);
        if (baby_name == null) {
            tv_baby_name.setText("- -");
        } else {
            tv_baby_name.setText(baby_name);
        }

        if (room_name == null) {
            tv_room_number.setText("- -");
        } else {
            tv_room_number.setText(room_name);
        }

        if (type.equals("1")) {
            tv_content.setText(getResources().getString(R.string.mamahuli) + "-" + title);
        } else if (type.equals("2")) {
            tv_content.setText(getResources().getString(R.string.baobaohuli) + "-" + title);
        }

        // 获取头部数据信息
        getStartHuliData();
        // 获取护理日志数据
        getHuliLogData(nid);
        lv_start_huli.setFocusable(false);

    }


    // 获取日志信息
    public void getHuliLogData(String nid) {
        RequestParams params = new RequestParams(GlobalConstants.URL);
        params.setCacheMaxAge(0);
        showDialog();
        JSONObject object = new JSONObject();
        try {
            object.put("pid", pid);
            object.put("type", type);
            object.put("nurse", nid);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        params.addBodyParameter("q", session + GlobalConstants.URL_HULI_LOG + object.toString());

        // LogUtils.d("params = " + params.toString());

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                JSONObject jsonObject = null;
                closeDialog();
                try {
                    jsonObject = new JSONObject(result);
                    LogUtils.d("result = " + jsonObject.toString());
                    HuLiLogEntity hle = GlobalConstants.gson.fromJson(jsonObject.toString(), HuLiLogEntity.class);
                    if (hle != null && hle.State.equals(GlobalConstants.SUCCESS_CODE)) {
                        lv_start_huli.setAdapter(new StartHuliLvAdapter(hle.Message, getApplicationContext(), pic, StartHuliActivity.this));
                        if (hle.Message.size() == 0) {
                            tv_no_data.setVisibility(View.VISIBLE);
                        } else {
                            tv_no_data.setVisibility(View.GONE);
                        }
                    } else {
                        tv_no_data.setVisibility(View.VISIBLE);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                tv_no_data.setVisibility(View.VISIBLE);
                closeDialog();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                closeDialog();
            }

            @Override
            public void onFinished() {
                closeDialog();
            }
        });
    }


    // 获取校验
    public void getStartHuliData() {
        if (session == null) {
            return;
        }
        RequestParams params = new RequestParams(GlobalConstants.URL);
        params.setCacheMaxAge(0);
        //showDialog();

        JSONObject object = new JSONObject();
        try {
            object.put("nurseid", nid);
            object.put("roomid", roomid);
            object.put("type", type);
            object.put("motherid", motherid);
            object.put("babyid", babyid);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        params.addBodyParameter("q", session + GlobalConstants.URL_HULI_TITLE + object.toString());
        // LogUtils.d("params = " + params.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                //closeDialog();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(result);
                    LogUtils.d("result = " + jsonObject.toString());
                    jye = GlobalConstants.gson.fromJson(jsonObject.toString(), JiaoYanEntity.class);
                    if (jye != null && jye.State.equals(GlobalConstants.SUCCESS_CODE)) {
                        if (jye.Message.start.equals("")) {
                            tv_jiaoyan.setText(R.string.jiaoyanbiaoqianbuxuyao);
                            isNeedCheck = false;
                        } else {
                            tv_jiaoyan.setText(R.string.jiaoyanbiaoqianxuyao);
                            isNeedCheck = true;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                //closeDialog();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                //closeDialog();
            }

            @Override
            public void onFinished() {
                //closeDialog();
            }
        });

    }

    public void showDialog() {
        myDialog = DialogUtils.createLoadingDialog(StartHuliActivity.this, getResources().getString(R.string.jiazaizhong));

    }

    public void closeDialog() {
        DialogUtils.closeDialog(myDialog);
    }

    // 设置图片
    private void setImageToView(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            Bitmap bitmap = extras.getParcelable("data");
            // 添加图片的逻辑
            if (position_img < al_Bitmaps.size()) {
                if (al_Bitmaps.get(position_img) != null) {
                    al_Bitmaps.remove(position_img);
                    al_imgs.remove(position_img);
                    al_Bitmaps.add(position_img, bitmap);
                } else {
                    al_Bitmaps.add(position_img, bitmap);
                }
            } else {
                al_Bitmaps.add(position_img, bitmap);
            }
            // bitmap保存到本地
            saveBitmapFile(bitmap);
            // 提交图片到服务器
            postPicToServer();
            gv_photo.setAdapter(new PhotoGvAdapter(
                    al_Bitmaps, getApplicationContext(), al_imgs, 5));
        }
    }

    public void saveBitmapFile(Bitmap bitmap) {
        // 创建文件夹
        File file = null;
        try {
            file = new File(Environment.getExternalStorageDirectory()
                    + File.separator + "hulibao_check" + File.separator);
            // 如果文件夹不存在就创建
            if (!file.exists()) {
                file.mkdir();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        File f = new File(Environment.getExternalStorageDirectory()
                + File.separator + "hulibao_check" + File.separator + "check_pic.jpg");
        try {
            FileOutputStream out = new FileOutputStream(f);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String getImagePath(Uri uri, String selection) {
        String path = null;
        Cursor cursor = this.getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    public static Uri getImageContentUri(Context context, File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[]{BaseColumns._ID}, MediaStore.MediaColumns.DATA + "=? ",
                new String[]{filePath}, null);

        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor.getColumnIndex(BaseColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.MediaColumns.DATA, filePath);
                return context.getContentResolver().insert(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }

    public String getRealPathFromUri(Context context, Uri contentUri) {
        Cursor cursor = null;
        try {
            String[] proj = {MediaStore.MediaColumns.DATA};
            cursor = context.getContentResolver().query(contentUri, proj, null,
                    null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }

    // 处理返回值
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // LogUtils.d("requestCode =" + requestCode);
        // LogUtils.d("resultCode =" + resultCode);
        // 数据选择返回逻辑
        if (requestCode == 1) {
            HuLiEntity.HuLiDetailData hdd_back = (HuLiEntity.HuLiDetailData) data.getSerializableExtra("back_data");
            String position = data.getStringExtra("position");
            if (hdd_back != null) {
//                LogUtils.d("back_data = " + hdd_back.selected_str);
//                LogUtils.d("position = " + position);
                // 将数据赋值给模型
                hd.v.get(Integer.parseInt(position)).selected_str = hdd_back.selected_str;
                showStartPop(Integer.parseInt(position), isNew);
            }
            // 二维码校验返回逻辑
        } else if (requestCode == CHECK_REQUESTCODE && resultCode == 3) {
            // 校验通过
            isNeedCheck = false;
            // LogUtils.d("return");
        } else if (requestCode == TAKE_PICTURE) {
            // 7.0
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                setImageToView(data);
            } else {
                startPhotoZoom(tempUri); // 开始对图片进行裁剪处理
            }
        } else if (requestCode == CHOOSE_PICTURE) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                try {
                    Uri uri = data.getData();
                    LogUtils.d("uri = " + uri);
                    if (String.valueOf(uri).substring(0, 4).equals("file")) {
                        // Log.i(TAG, "uri = " + uri);
                        File myFile = new File(uri.getPath());
                        Uri selectedImage = getImageContentUri(
                                this, myFile);
                        // Log.i(TAG, "selectedImage = " + selectedImage);
                        String realpath = getRealPathFromUri(
                                this, selectedImage);
                        // Log.i(TAG, "realpath = " + realpath);
//                                PreUtils.setParam(mainActivity,
//                                        GlobalContants.PHOTO_PATH, realpath);
                        BitmapFactory.Options options = new BitmapFactory.Options();
                        options.inSampleSize = 6;// 图片宽高都为原来的二分之一，即图片为原来的四分之一
                        Bitmap bitmap = BitmapFactory
                                .decodeFile(realpath, options);
                        if (position_img < al_Bitmaps.size()) {
                            if (al_Bitmaps.get(position_img) != null) {
                                al_Bitmaps.remove(position_img);
                                al_imgs.remove(position_img);
                                al_Bitmaps.add(position_img, bitmap);
                            } else {
                                al_Bitmaps.add(position_img, bitmap);
                            }
                        } else {
                            al_Bitmaps.add(position_img, bitmap);
                        }
                        // bitmap保存到本地
                        saveBitmapFile(bitmap);
                        // 提交图片到服务器
                        postPicToServer();
                        gv_photo.setAdapter(new PhotoGvAdapter(
                                al_Bitmaps, getApplicationContext(), al_imgs, 5));
                    } else if (String.valueOf(uri).substring(0, 7)
                            .equals("content")) {
                        String imagePath = null;
                        Log.d("uri=intent.getData :", "" + uri);
                        if (DocumentsContract.isDocumentUri(this, uri)) {
                            String docId = DocumentsContract.getDocumentId(uri);        //数据表里指定的行
//                                    Log.d("getDocumentId(uri) :", "" + docId);
//                                    Log.d("uri.getAuthority() :", "" + uri.getAuthority());
                            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                                String id = docId.split(":")[1];
                                String selection = MediaStore.Images.Media._ID + "=" + id;
                                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
                            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                                imagePath = getImagePath(contentUri, null);
                            }

                        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
                            imagePath = getImagePath(uri, null);
                        }

                        BitmapFactory.Options options = new BitmapFactory.Options();
                        options.inSampleSize = 10;// 图片宽高都为原来的十分之一，即图片为原来的四分之一
                        Bitmap bitmap = BitmapFactory.decodeFile(imagePath,
                                options);
                        if (position_img < al_Bitmaps.size()) {
                            if (al_Bitmaps.get(position_img) != null) {
                                al_Bitmaps.remove(position_img);
                                al_imgs.remove(position_img);
                                al_Bitmaps.add(position_img, bitmap);
                            } else {
                                al_Bitmaps.add(position_img, bitmap);
                            }
                        } else {
                            al_Bitmaps.add(position_img, bitmap);
                        }
                        // bitmap保存到本地
                        saveBitmapFile(bitmap);
                        // 提交图片到服务器
                        postPicToServer();
                        gv_photo.setAdapter(new PhotoGvAdapter(
                                al_Bitmaps, getApplicationContext(), al_imgs, 5));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                startPhotoZoom(data.getData()); // 开始对图片进行裁剪处理
            }
        } else if (requestCode == CROP_SMALL_PICTURE) {
            if (data != null) {
                setImageToView(data); // 让刚才选择裁剪得到的图片显示在界面上
            }
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (MyUtils.isShouldHideInput(v, ev)) {
                if (MyUtils.hideInputMethod(this, v)) {
                    return true; //隐藏键盘时，其他控件不响应点击事件==》注释则不拦截点击事件
                }
            }
        }
        return super.dispatchTouchEvent(ev);
    }
}
